package org.example.demo;

import com.intellij.openapi.components.PersistentStateComponent;
import com.intellij.openapi.components.State;
import com.intellij.openapi.components.Storage;
import com.intellij.openapi.project.Project;
import com.intellij.util.xmlb.XmlSerializerUtil;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

@State(
    name = "KingbaseDataSourceConfig",
    storages = @Storage("kingbaseDataSource.xml")
)
public class DataSourceConfig implements PersistentStateComponent<DataSourceConfig> {

    public String dbType = "Kingbase";
    public String host = "localhost";
    public int port = 54321;
    public String database = "testdb";
    public String username = "system";
    public String password = "";
    public String aiKey = "";

    public static DataSourceConfig getInstance(Project project) {
       return project.getService(DataSourceConfig.class);
    }

    // ✅ 不需要 getInstance，改用 project.getService()
    // （但必须先注册服务）

    @Override
    public @Nullable DataSourceConfig getState() {
        return this;
    }

    @Override
    public void loadState(@NotNull DataSourceConfig state) {
        XmlSerializerUtil.copyBean(state, this);
    }

    public String getDriverClass() {
        return switch (dbType.toLowerCase()) {
            case "kingbase" -> "com.kingbase8.Driver";
            case "postgresql" -> "org.postgresql.Driver";
            case "mysql" -> "com.mysql.cj.jdbc.Driver";
            default -> "com.kingbase8.Driver";
        };
    }

    public String getJdbcUrl() {
        return switch (dbType.toLowerCase()) {
            case "kingbase" -> "jdbc:kingbase8://" + host + ":" + port + "/" + database;
            case "postgresql" -> "jdbc:postgresql://" + host + ":" + port + "/" + database;
            case "mysql" -> "jdbc:mysql://" + host + ":" + port + "/" + database;
            default -> "jdbc:kingbase8://" + host + ":" + port + "/" + database;
        };
    }
}